package java8action.chapter03;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public class FunctionInterfaceDemo {

    /**
     * predicate 是断言 返回TRUE or FALSE
     *
     * @param list 待判断的元素
     * @param p    断言
     * @param <T>  具体类型
     * @return
     */
    public <T> List<T> filter(List<T> list, Predicate<T> p) {
        List<T> result = new ArrayList<>();
        list.forEach(item -> {
            if (p.test(item)) {
                result.add(item);
            }
        });
        return result;
    }

    /**
     * 测试用例
     */
    @Test
    public void testFilter() {
        Predicate<String> predicate = (String s) -> s.length() > 3;
        List<String> list = new ArrayList<>();
        list.add("11");
        list.add("1234");
        List<String> filter = filter(list, predicate);
        System.out.println(filter);
    }


    /**
     * accept 就是 (Integer i) -> System.out.println("i-->" + i)
     * consumer是消费数据 不返回数据
     *
     * @param list
     * @param c
     * @param <T>
     */
    public <T> void forEach(List<T> list, Consumer<T> c) {
        for (T s : list) {
            c.accept(s);
        }
    }

    @Test
    public void testForEach() {
        List<Integer> list = Arrays.asList(1, 2, 3);
        forEach(list, (Integer i) -> System.out.println("i-->" + i));
    }

    public <T, R> List<R> map(List<T> list, Function<T, R> f) {
        List<R> ret = new ArrayList<>();
        for (T s : list) {
            // todo 执行的结果返回
            ret.add(f.apply(s));
        }
        return ret;
    }

    @Test
    public void testMap() {
        List<Integer> list = map(Arrays.asList("11", "222"), String::length);
        System.out.println(list);
    }
}
